//
//  UUProductVC.m
//  UUCharterSupplier
//
//  Created by ZhangAo on 03/02/2018.
//  Copyright © 2018 UUCharter. All rights reserved.
//

#import "UUProductVC.h"
#import "UUResourceManager.h"
#import "UUPermissionManager.h"
#import "UUProductManager.h"
#import "UUProductEditVC.h"
#import "UUProductStateListVC.h"
#import "UUBaseTableViewCell.h"
#import <WZLBadge/WZLBadgeImport.h>

@interface UUProductMenuCell : UUBaseTableViewCell

@property (nonatomic, strong) UILabel *titleLabel;

@end

@implementation UUProductMenuCell

- (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier {
    self = [super initWithStyle:style reuseIdentifier:reuseIdentifier];
    if (self) {
        self.showSeparator = NO;
        
        self.titleLabel = [UILabel new];
        self.titleLabel.font = [UIFont systemFontOfSize:14];
        self.titleLabel.textAlignment = NSTextAlignmentLeft;
        self.titleLabel.textColor = RGB_COLOR(80, 80, 80);
        [self.contentView addSubview:self.titleLabel];
        [self.titleLabel mas_makeConstraints:^(MASConstraintMaker *make) {
            make.center.mas_equalTo(0);
        }];
    }
    return self;
}

@end

/////////////////////////////////////////////////////////////////////////////

#define CarCategoryAll          (@(-1))

@interface UUProductVC () <UITableViewDelegate, UITableViewDataSource, UUProductManagerObserver>

@property (nonatomic, strong) UITableView *menuTableView;

@property (nonatomic, copy) NSArray<NSNumber *> *carCategoryIds;
@property (nonatomic, strong) NSNumber *currentCategoryId;

@property (nonatomic, strong) UUProductStateListVC *onlineListVC;
@property (nonatomic, strong) UUProductStateListVC *offlineListVC;
@property (nonatomic, strong) UUProductStateListVC *reviewRejectListVC;

@property (nonatomic, weak) DKPagingMenuItem *deniedItem;

@end

@implementation UUProductVC

- (void)viewDidLoad {
    [super viewDidLoad];
    
    if ([GetPermissionManager() checkPermission:UUPermissionFlagProductReadWrite]) {
        self.navigationItem.rightBarButtonItem = [UIBarButtonItem barButtonItemWithTitle:GetResourceManager().addIconText
                                                                                  target:self
                                                                                selector:@selector(addProduct)];
    }
    
    self.menuTableView = [[UITableView alloc] initWithFrame:CGRectZero style:UITableViewStylePlain];
    self.menuTableView.delegate = self;
    self.menuTableView.dataSource = self;
    self.menuTableView.rowHeight = 55;
    [self.menuTableView registerClass:[UUProductMenuCell class] forCellReuseIdentifier:@"Cell"];
    [self.view addSubview:self.menuTableView];
    [self.menuTableView mas_makeConstraints:^(MASConstraintMaker *make) {
        make.top.equalTo(self.mas_topLayoutGuideBottom);
        make.left.bottom.mas_equalTo(0);
        make.width.mas_equalTo(85);
    }];

    [self reloadCarCategories];
    self.currentCategoryId = CarCategoryAll;
    
    NSMutableArray<DKPagingMenuItem *> *items = [NSMutableArray arrayWithCapacity:3];
    
    self.onlineListVC = [UUProductStateListVC listWithReviewStatus:nil
                                                      onlineStatus:@[@(UUProductOnlineStatusOnline), @(UUProductOnlineStatusApplicationToOffline)]
                                                     carCategoryId:nil];
    DKPagingMenuItem *verifiedItem = [[DKPagingMenuItem alloc] initWithTitle:@"已上架"
                                                          menuViewController:self.onlineListVC];
    [items addObject:verifiedItem];
    
    self.offlineListVC = [UUProductStateListVC listWithReviewStatus:@[@(UUProductReviewStatusApproval), @(UUProductReviewStatusWaitingForReview)]
                                                       onlineStatus:@[@(UUProductOnlineStatusOffline)]
                                                      carCategoryId:nil];
    DKPagingMenuItem *verifyItem = [[DKPagingMenuItem alloc] initWithTitle:@"未上架"
                                                        menuViewController:self.offlineListVC];
    [items addObject:verifyItem];
    
    self.reviewRejectListVC = [UUProductStateListVC listWithReviewStatus:@[@(UUProductReviewStatusRejected)]
                                                            onlineStatus:nil
                                                           carCategoryId:nil];
    DKPagingMenuItem *deniedItem = [[UUPagingMenuItem alloc] initWithTitle:@"已拒绝"
                                                        menuViewController:self.reviewRejectListVC];
    [items addObject:deniedItem];
    
    UUPagingMenuController *tabPageVC = [[UUPagingMenuController alloc] initWithItems:items];
    tabPageVC.scrollView.scrollEnabled = NO;
    [self addChildViewController:tabPageVC];
    [self.view addSubview:tabPageVC.view];
    [tabPageVC.view mas_makeConstraints:^(MASConstraintMaker *make) {
        make.bottom.equalTo(self.menuTableView);
        make.left.equalTo(self.menuTableView.mas_right).offset(5);
        make.right.mas_equalTo(0);
        make.top.equalTo(self.mas_topLayoutGuideBottom);
    }];
    
    self.deniedItem = deniedItem;
    
    [GetProductManager() asyncUpdateProducts];
    [GetProductManager() addObserver:self];
}

- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    
    [self updateDeniedBadge];
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

- (void)updateDeniedBadge {
    id categoryId = self.currentCategoryId;
    if ([self.currentCategoryId isEqual:CarCategoryAll]) {
        categoryId = nil;
    }
    
    NSInteger count = [GetProductManager() fetchProductsWithReviewStatus:@[@(UUProductReviewStatusRejected)]
                                                            onlineStatus:nil
                                                           carCategoryId:categoryId].count;
    [self.deniedItem.view showBadgeWithStyle:WBadgeStyleNumber
                                       value:count
                               animationType:WBadgeAnimTypeNone];
}

- (void)addProduct {
    UUProductEditVC *editVC = [UUProductEditVC instanceOfAppropriate];
    editVC.editable = YES;
    editVC.preferredCarCategoryId = self.currentCategoryId;
    [self.navigationController pushViewController:editVC animated:YES];
}

- (void)reloadCarCategories {
    NSMutableArray<NSNumber *> *carCategoryIds = [[GetCarCategoryManager() fetchCarCategories] mutableCopy];
    if (![carCategoryIds containsObject:self.currentCategoryId]) {
        self.currentCategoryId = self.carCategoryIds.firstObject;
    }
    
    [carCategoryIds insertObject:CarCategoryAll atIndex:0];
    
    self.carCategoryIds = carCategoryIds;
    
    [self.menuTableView reloadData];
}

#pragma mark - UITableViewDelegate, UITableViewDataSource methods

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView {
    return 1;
}

- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return self.carCategoryIds.count;
}

- (UIView *)tableView:(UITableView *)tableView viewForFooterInSection:(NSInteger)section {
    return [UIView new];
}

- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    UUProductMenuCell *cell = [tableView dequeueReusableCellWithIdentifier:@"Cell" forIndexPath:indexPath];
    
    NSNumber *carCategoryId = self.carCategoryIds[indexPath.row];
    
    if ([carCategoryId isEqual:CarCategoryAll]) {
        cell.titleLabel.text = @"全部";
    } else {
        UUCarCategoryModel *carCategory = [GetCarCategoryManager() fetchCarCategoryWithCategoryId:carCategoryId];
        
        cell.titleLabel.text = carCategory.name;
    }
    
    if ([self.currentCategoryId isEqual:carCategoryId]) {
        [tableView selectRowAtIndexPath:indexPath animated:NO scrollPosition:UITableViewScrollPositionNone];
    } else {
        [tableView deselectRowAtIndexPath:indexPath animated:NO];
    }
    
    return cell;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    self.currentCategoryId = self.carCategoryIds[indexPath.row];
    
    id categoryId = self.currentCategoryId;
    if ([self.currentCategoryId isEqual:CarCategoryAll]) {
        categoryId = nil;
    }
    
    [self.onlineListVC updateCarCategoryId:categoryId];
    [self.offlineListVC updateCarCategoryId:categoryId];
    [self.reviewRejectListVC updateCarCategoryId:categoryId];
    
    [self updateDeniedBadge];
}

#pragma mark - UUProductManagerObserver methods

- (void)productManagerDidUpdateProducts:(NSArray<NSNumber *> *)products {
    [self updateDeniedBadge];
}

- (void)productManagerDidRemoveProducts:(NSArray<NSNumber *> *)products {
    [self updateDeniedBadge];
}

@end
